import java.util.Arrays;

public class Solution132 {

    public int minCut(String s) {
        int n = s.length();
        boolean[][] f = new boolean[n][n];

        for (int i = 0; i < n; i++) {
            Arrays.fill(f[i], true);
        }
        for (int i = n; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                f[i][j] = (s.charAt(i) == s.charAt(j)) && f[i + 1][j - 1];
            }
        }

        int[] dp = new int[n];
        dp[0] = 0;
        for (int i = 1; i < n; i++) {
            if (f[0][i]) {
                dp[i] = 0;
            } else {
                dp[i] = dp[i - 1] + 1;
                for (int j = 1; j < i; j++) {
                    if (f[j][i]) {
                        dp[i] = Math.min(dp[i], dp[j - 1] + 1);
                    }
                }
            }
        }
        return dp[n - 1];
    }
    /*
    超时
    int dfs(String s, int start) {
        if (start == s.length()) {
            return -1;
        }
        int min = s.length() - start;
        for (int i = start; i < s.length(); i++) {
            if (f[start][i]) {
                min = Math.min(min, dfs(s, i + 1) + 1);
            }
        }
        return min;
    }
    */
}
